﻿@model object
@{
    Layout = ViewBag.Layout ?? "~/Views/Shared/EditorTemplates/_TR.cshtml";
    ViewData.TemplateInfo.HtmlFieldPrefix = ViewData.TemplateInfo.HtmlFieldPrefix.Replace(ViewData.ModelMetadata.PropertyName, "").Trim('.');
    var propertyName = ViewData["name"] == null ? ViewData.ModelMetadata.PropertyName : ViewData["name"].ToString();
    var fieldId = ViewData.TemplateInfo.GetFullHtmlFieldId(propertyName);

    var editorHtmlAttributes = Html.GetUnobtrusiveValidationAttributes(propertyName, ViewData.ModelMetadata);
    var htmlAttributes = ViewBag.HtmlAttributes;
    if (htmlAttributes != null)
    {
        if (htmlAttributes is IDictionary<string, object>)
        {
            editorHtmlAttributes.Merge((IDictionary<string, object>)htmlAttributes);
        }
        else
        {
            editorHtmlAttributes.Merge(new RouteValueDictionary(htmlAttributes));
        }
    }

    var selectName = "select_" + propertyName;
}


<div id="@(fieldId + "_dropdown")">
    @Html.DropDownList(selectName, ViewData.ModelMetadata.GetDataSource()
                    .GetSelectListItems(ViewContext.RequestContext, "").SetActiveItem(Model), new RouteValueDictionary(editorHtmlAttributes).Merge("disabled", "disabled"))
    <a class="action" id="@(fieldId + "_createNew")" title="@("Switch".Localize())">@Html.IconImage("switch")</a>
    @Html.ValidationMessageForInput(selectName)

</div>

<div id="@(fieldId + "_textbox")">
    @Html.TextBox(propertyName, Model, editorHtmlAttributes)
    <a class="action" id="@(fieldId + "_cancel")" title="@("Switch".Localize())">@Html.IconImage("switch")</a>

    @Html.ValidationMessage(ViewData.ModelMetadata, new { name = ViewData["name"] })

</div>
@Html.Hidden("CreateNew", "false")

@if (!string.IsNullOrEmpty(ViewData.ModelMetadata.Description))
{
    <em class="tip">@Html.Raw(ViewData.ModelMetadata.Description.Localize())</em>
}
<script>
    jQuery(function ($) {
        //$("select[name=@fieldId]").select2({ minimumResultsForSearch: 20 });
        var dropdownField = $('#@(fieldId + "_dropdown")');
        var textboxField = $('#@(fieldId + "_textbox")');
        var createNew = $('#@(fieldId + "_createNew")');
        var cancel = $('#@(fieldId + "_cancel")');
        var property = $('input[name=@propertyName]');
        textboxField.show();
        dropdownField.hide();
        createNew.click(function () {
            dropdownField.find('select').attr('disabled', true);
            dropdownField.hide();
            textboxField.show();

            property.val('');
            $('input[name=CreateNew]').val('true');
        });
        cancel.click(function () {
            dropdownField.find('select').removeAttr('disabled');

            textboxField.hide();
            dropdownField.show();

            $('input[name=CreateNew]').val('false');
        });

        $('#@selectName').change(function () {
            property.val($(this).val());
        });
    });
</script>
